package com.kl.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.Locale;
import java.util.Map;

/**
 * freemarker工具类
 *
 * @author xr_zjb
 * @date 2017/10/18 13:16
 *
 */
public class FreemarkerUtil {

    /**
     * 模板生成
     * @param templateStr
     * @param data
     * @return
     */
    public static String temstrCreate(String templateStr, Map data){
        if(StringUtils.isEmpty(templateStr) || data == null){
            return null;
        }
        Configuration cfg = new Configuration();
        cfg.setTemplateLoader(new StringTemplateLoader(templateStr));
        cfg.setDefaultEncoding("UTF-8");

        Template template = null;
        try {
            template = cfg.getTemplate("");

            StringWriter writer = new StringWriter();
            template.process(data, writer);
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ftl模板
     */
    public static String relativeFtlPath="/ftl/";

    /**
     * 邮件 系统严重日志html模板
     */
    public static String mailLogginfFtlPath="mail/loggingInfo.ftl";

    /**
     * 实体类模板
     */
    public static String modelFtlPath="generate/adus/model/model.ftl";

    /**
     * mapper模板
     */
    public static String mapperFtlPath="generate/adus/dao/mapper.ftl";

    /**
     * mapping xml模板
     */
    public static String mappingFtlPath="generate/adus/dao/mapping.ftl";

    /**
     * service模板
     */
    public static String serviceFtlPath="generate/adus/service/service.ftl";

    /**
     * serviceImpl 模板
     */
    public static String serviceImplFtlPath="generate/adus/service/serviceImpl.ftl";

    /**
     * bo模板
     */
    public static String boFtlPath="generate/adus/bo/bo.ftl";

    /**
     * controller 模板
     */
    public static String controllerFtlPath="generate/adus/controller/controller.ftl";

    /**
     * view add 模板
     */
    public static String viewAddFtlPath="generate/adus/view/add.ftl";

    /**
     * view edit 模板
     */
    public static String viewEditFtlPath="generate/adus/view/edit.ftl";

    /**
     * view list 模板
     */
    public static String viewListFtlPath="generate/adus/view/list.ftl";

    /**
     * view ajaxList 模板
     */
    public static String viewAjaxFtlPath="generate/adus/view/ajaxList.ftl";


    /**
     * 生成静态页面主方法     默认编码为UTF-8
     * @param context ServletContext
     * @param data 一个Map的数据结果集
     * @param templatePath ftl模版路径
     * @param filePath 生成的路径
     * @throws TemplateException
     * @throws IOException
     */
    public static void create(ServletContext context, Map<String,Object> data, String templatePath, String filePath) throws IOException, TemplateException{
        create(context, data, "UTF-8", templatePath, "UTF-8", filePath);
    }
    /**
     * 生成静态页面主方法
     * @param context ServletContext
     * @param data 一个Map的数据结果集
     * @param templatePath ftl模版路径
     * @param jspPath 生成静态页面的路径
     * @param jspEncode 生成静态页面的编码
     * @throws IOException
     * @throws TemplateException
     */
    public static void create(ServletContext context,Map<String,Object> data,String templetEncode,String templatePath,String jspEncode,String jspPath) throws IOException, TemplateException{

        Configuration freemarkerCfg=initCfg(context, templetEncode);

        //指定模版路径
        Template template = freemarkerCfg.getTemplate(templatePath,templetEncode);
        template.setEncoding(templetEncode);
        //静态页面路径
        File htmlFile = new File(jspPath);
        if (!htmlFile.getParentFile().exists()) {
            htmlFile.getParentFile().mkdirs();
        }
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), jspEncode));
        //处理模版
        template.process(data, writer);
        writer.flush();
        writer.close();
    }

    /**
     * 处理页面后，装处理结果放入指定Out
     * @param context
     * @param data
     * @param templatePath
     * @throws TemplateModelException
     */
    public static void createWriter(ServletContext context,Map<String,Object> data,String templatePath,Writer writer) throws TemplateModelException{
        createWriter(context, data, "UTF-8", templatePath, "UTF-8",writer);
    }
    public static void createWriter(ServletContext context,Map<String,Object> data,String templetEncode,String templatePath,String htmlEncode,Writer writer) throws TemplateModelException{
        Configuration freemarkerCfg=initCfg(context, templetEncode);
        try {
            //指定模版路径
            Template template = freemarkerCfg.getTemplate(templatePath,templetEncode);
            template.setEncoding(templetEncode);
            //处理模版
            template.process(data, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取freemarker teplate
     * @param context
     * @param templatePath
     * @param templetEncode
     * @return
     * @throws TemplateModelException
     * @throws IOException
     */
    private static Template getTemplate(ServletContext context,String templatePath,String templetEncode) throws TemplateModelException, IOException{
        Configuration freemarkerCfg=initCfg(context, templetEncode);
        //指定模版路径
        Template template = freemarkerCfg.getTemplate(templatePath,templetEncode);
        template.setEncoding(templetEncode);
        return template;
    }

    /**
     * String
     * @param context
     * @param data
     * @param templatePath
     * @param templetEncode
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public static String getTemplateText(ServletContext context,Map data ,String templatePath,String templetEncode) throws IOException, TemplateException{
        Template template = getTemplate(context,templatePath,templetEncode);
        return FreeMarkerTemplateUtils.processTemplateIntoString(template,data);
    }

    /**
     * 初始化freemarker配置
     * @return
     * @throws TemplateModelException
     */
    public static Configuration initCfg(ServletContext context,String templetEncode) throws TemplateModelException{
        Configuration freemarkerCfg=null;
        //判断context中是否有freemarkerCfg属性
        if (context!=null&&context.getAttribute("freemarkerCfg")!=null) {
            freemarkerCfg=(Configuration)context.getAttribute("freemarkerCfg");
        }else{
            freemarkerCfg = new Configuration();
            //加载模版
            freemarkerCfg.setClassForTemplateLoading(new FreemarkerUtil().getClass(), relativeFtlPath);
            //freemarkerCfg.setServletContextForTemplateLoading(context, relativeFtlPath);
            freemarkerCfg.setEncoding(Locale.getDefault(), templetEncode);
        }
        //freemarkerCfg.setTemplateUpdateDelay(20000);  // 设置模板缓存
        //freemarkerCfg.clearTemplateCache(); // 清除模板缓存
        return freemarkerCfg;
    }


}
